/**
 * ReportGear(2011)
 */
package com.reportgear.designer.gui.component.date;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 单选Combobox模型，用于日期选择
 * 
 * @version 1.0 2011-4-26
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class SingleObjectComboBoxModel extends AbstractListModel implements ComboBoxModel {
	/**
	 * UID
	 */
	private static final long serialVersionUID = 1268899957232637046L;

	private static final Logger logger = LoggerFactory.getLogger(SingleObjectComboBoxModel.class.getName());

	private SimpleDateFormat dateFormat;
	private String selectedDate = "";

	public SingleObjectComboBoxModel() {
	}

	public SingleObjectComboBoxModel(SimpleDateFormat format) {
		setDateFormat(format);
	}

	public void setDateFormat(SimpleDateFormat format) {
		this.dateFormat = format;
	}

	public SimpleDateFormat getDateFormat() {
		return this.dateFormat;
	}

	public void setSelectedItem(Object item) {
		if (item == null)
			return;
		if (item instanceof Date) {
			try {
				this.selectedDate = this.dateFormat.format((Date) item);
			} catch (Exception ex) {
				if (logger.isDebugEnabled()) {
					logger.debug(ex.getMessage(), ex);
				}
			}
		} else {
			try {
				String str1 = item.toString().trim();
				if ((str1.length() != 10) && (str1.length() != 19)) {
					return;
				}

				String str2 = this.dateFormat.toPattern();
				if ((str1.length() == 10) && (str2.length() == 19)) {
					str1 = str1 + this.selectedDate.substring(10);
				}

				this.dateFormat.parse(str1);
				this.selectedDate = str1;
			} catch (Exception ex) {
				throw new UnsupportedOperationException("无效日期时间格式: 字符串 [" + item + "],格式为["
						+ this.dateFormat.toPattern() + "]。");
			}
		}

		fireContentsChanged(this, -1, -1);
	}

	public Object getSelectedItem() {
		return this.selectedDate;
	}

	public Object getElementAt(int index) {
		return this.selectedDate;
	}

	public int getSize() {
		return 1;
	}
}